package com.hwy.catering.interceptor;

import com.hwy.catering.utils.UserHolder;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.hwy.catering.utils.ConstantPool.TOKEN_KEY;

/**
 * 权限拦截器
 */
public class RootInterceptor implements HandlerInterceptor {

    //LoginInterceptor为我们手动创建的对象，不是spring创建的，没有用到依赖注入，所以不能用@Resource导入
    private StringRedisTemplate stringRedisTemplate;

    //手动导入stringRedisTemplate
    public RootInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(TOKEN_KEY  + token);
        if (userMap.size() == 0){
//            System.out.println("当前账号未登录");
            return true;
        }else if (userMap.get("isRoot").equals("0")){
//            System.out.println("管理员账号");
            return true;
        }else if (userMap.get("isRoot").equals("1")){
//            System.out.println("普通账号");
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //有个bug，不知道为什么会出现一个 login:token:null 的redis-key，这里手动清除掉吧
        stringRedisTemplate.delete("login:token:null");
    }
}
